/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package nl.cloudfarming.client.planning.tactical;

import java.beans.IntrospectionException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Date;
import java.util.List;
import nl.cloudfarming.client.area.field.PartFieldLayer;
import nl.cloudfarming.client.model.ProductionUnit;
import nl.cloudfarming.client.model.FieldPlan;
import nl.cloudfarming.client.planning.PlanEventKey;
import nl.cloudfarming.eventbus.GuiEvent;
import nl.cloudfarming.eventbus.GuiEventBus;
import nl.cloudfarming.eventbus.GuiEventKey;
import nl.cloudfarming.eventbus.GuiEventListener;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Node;
import org.openide.util.Exceptions;

/**
 * Factory which provides ProductionUnitNodes.
 * @author Timon Veenstra
 */
public class ProductionUnitNodeFactory extends ChildFactory<ProductionUnit> implements PropertyChangeListener{

    private final FieldPlan fieldPlan;
    private final TacticalPlanningService service;

    public ProductionUnitNodeFactory(FieldPlan fieldPlan, TacticalPlanningService service) {
        this.fieldPlan = fieldPlan;
        this.service = service;
        init();
    }
    
    public final void init(){
        fieldPlan.addPropertyChangeListener("productionUnit", this);
    }
    
    @Override
    protected Node createNodeForKey(ProductionUnit key) {
        try {
            PartFieldLayer partFieldlayer = new PartFieldLayer(key.getName(), new Date(), service);
            return new ProductionUnitNode(partFieldlayer, key);
        } catch (IntrospectionException ex) {
            Exceptions.printStackTrace(ex);
            return null;
        }
    }

    @Override
    protected boolean createKeys(List<ProductionUnit> toPopulate) {
        toPopulate.addAll(fieldPlan.getProductionUnits());
        return true;
    }

    /**
     * Listens to changes of the productionUnit 
     * @param evt 
     */
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        refresh(true);
    }
}
